Interactive plotting in Jupyter with matplotlib

Published

April 16, 2020

This is a little demo on how to make interactive plots with matplotlib and ipympl.

#!pip install ipywidgets matplotlib scipy numpy ipympl
%matplotlib widget
from matplotlib import pyplot as plt
from scipy.stats import johnsonsu, norm, t
from ipywidgets import interact, widgets
import numpy as np
x = np.linspace(-5, 5, 1000)

fig = plt.figure()
plt.plot(x, norm.pdf(x), label="normal")
line, = plt.plot(x, x, label="other")
plt.legend()
plt.ylim(0, 1)

def update(a, b, which):
    if which == "Johnson SU":
        y = johnsonsu.pdf(x, a, np.exp(b))
    elif which == "Student-t":
        y = t.pdf(x, np.exp(b))
    line.set_ydata(y)
    fig.canvas.draw_idle()
    
interact(update,
         a=(-10.0, 10.0),
         b=widgets.FloatSlider(0.0, min=-10.0, max=5.0),
         which=["Johnson SU", "Student-t"]);